package com.tlxch.controller.student;

import com.tlxch.constant.JwtClaimsConstant;
import com.tlxch.dto.SStudentdto;
import com.tlxch.dto.SupdatePwddto;
import com.tlxch.pojo.SStudent;
import com.tlxch.pojo.TTeacher;
import com.tlxch.properties.JwtProperties;
import com.tlxch.result.Result;
import com.tlxch.server.student.StudentService;
import com.tlxch.utils.JwtUtil;
import com.tlxch.utils.MD5Utils;
import com.tlxch.vo.StudentLoginvo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Api(tags = "学生相关接口")
@Slf4j
@RestController
@RequestMapping("/student/student")
public class StudentController {

    @Autowired
    StudentService studentService;
    @Autowired
    MD5Utils md5Utils;
    @Autowired
    JwtProperties jwtProperties;

    @PostMapping("/login")
    @ApiOperation("学生登录")
    public Result<StudentLoginvo> tLogin(@RequestBody SStudent student){
        SStudent sStudent = studentService.slogin(student);
        String password = md5Utils.MD5Lower(student.getsPassword());
        if (sStudent == null) {
            return Result.error("没有该学生信息");
        }else if(!sStudent.getsPassword().equals(password)){
            return Result.error("密码错误");
        }
        Map<String,Object> claims = new HashMap();
        claims.put(JwtClaimsConstant.USER_ID,sStudent.getsSid());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);
        System.out.println(jwtProperties.getUserSecretKey());
        StudentLoginvo teacherLoginvo = StudentLoginvo.builder()
                .sStudent(sStudent)
                .token(token)
                .build();
        return Result.success(teacherLoginvo);
    }

    @PutMapping("/updateInfo")
    @ApiOperation("修改学生信息")
    public Result updateInfo(@RequestBody SStudentdto studentdto){
        log.info("修改学生信息:{}",studentdto);
        studentService.updateInfo(studentdto);
        return Result.success();
    }

    @PutMapping("/updatePassword")
    @ApiOperation("修改学生密码")
    public Result updatePassword(@RequestBody SupdatePwddto student){
        SStudent sStudent = studentService.getbysid(student.getsSid());
        String password = md5Utils.MD5Lower(student.getsPassword());
        if (!Objects.equals(sStudent.getsPassword(), password)){
            return Result.error("原密码错误");
        }
        if (student.getrPassword().equals(student.getsPassword())){
            return Result.error("新密码不能与原密码相同");
        }
        String newPassword = md5Utils.MD5Lower(student.getrPassword());
        student.setrPassword(newPassword);
        studentService.updatePassword(student);
        return Result.success();
    }
}
